﻿using Microsoft.Extensions.Caching.Memory;

namespace Chaotic.DataBase.DBAccessLibrary.Common
{
    public static class MemoryCacheManager
    {
        private static readonly IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
        public static bool SetCache(string key, object? value, int minutes)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            bool result = false;
            try
            {
                TimeSpan slidingExpiration = new TimeSpan(0, minutes, 0);
                _cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    SlidingExpiration = slidingExpiration
                }); 
                result = true;
            }
            catch
            {
                // ignored
            }

            return result;
        }

        public static T? GetCache<T>(string key) where T : class
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            } 
            return _cache.Get<T>(key);
        }

        public static bool IsCacheExist(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            bool result = false;
            object? obj = _cache.Get(key);
            if (obj != null)
            {
                result = true;
            }
            return result;
        }

        public static void RemoveCache(string key)
        {
            if (!string.IsNullOrEmpty(key))
            {
                _cache.Remove(key);
            }
        }
    }

}
